<template>
    <div class="waitConfirmed">
        <search :columns="searchData" @getSearch="getSearch(arguments)" key="search"></search>
        <div class="mt16 list-layout">
          <div class="btns clear">
            <span class="title">{{ $t('common.listInformation') }}</span>
            <Button  @click="handleBatchDisabled"
                    v-if="delIds.length && permission.dcmMaintainDisableRecordBatchDisable">
              {{ $t('maintenance.Disable') }}
            </Button>
            <Button  @click="handleBatchDelete"
                    v-if="delIds.length && permission.dcmMaintainPlanDeleteBatch">{{ $t('common.Delete') }}
            </Button>
            <slot name="btns">

            </slot>
            <Button @click="getTableColumns(columns)">{{ handleContextMenuStatus ? $t('显示操作栏'):$t('隐藏操作栏') }}</Button>
          </div>
          <div class="tableContent">
            <Table border  class="resizable-table" @on-column-width-resize="onColumnWidthResize" ref="selection" :columns="columnsList" :data="data" @on-selection-change="onSelectChange">
              <template slot-scope="{ row }" slot="action">
                    <span class="operationBtn" @click="confirm(row)"
                          v-if="new Date(row.planEndTime).getTime() >= new Date().getTime() && permission.dcmMaintainDisableRecordEnable"><i class="iconfont zy-common-jinyong"></i>启用</span>
                <span class="operationBtn" @click="look(row)" v-if="permission.dcmMaintainPlanQueryById"><i class="iconfont zy-common-shezhi"></i>{{ $t('common.Check') }}</span>
                <span class="operationBtn" @click="edit(row)" v-if="permission.dcmMaintainPlanEdit"><i class="iconfont zy-common-shezhi"></i>{{ $t('common.Edit') }}</span>
                <span class="operationBtn" @click="deleteRow(row)" v-if="permission.dcmMaintainPlanDelete"><i class="iconfont zy-common-shezhi"></i>{{ $t('common.Delete') }}</span>
              </template>
            </Table>
          </div>
          <div class="pageWrap mt16">
            <pageLeftTitle :total="total" :selected="delIds.length" />
            <Page :total="total" :page-size="pageSize" :page-size-opts="$variable.pageSizes" :current="pageNum"
                  @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total/>
          </div>
        </div>
        <Modal :mask-closable="false"
            v-model="delFaultCodeShowF"
            title=""
        >
            <Row class="enableContent">
                <Col span="24" class="enableContentInner">
                    <img width="95px" src="~images/event/del.png" alt="">
                </Col>
                <Col span="24" class="enableTips">
                    <span>{{$t('maintenance.delTip')}}</span>
                </Col>
            </Row>
            <div slot="footer">
                <Button type="default" @click="delFaultCodeShowF = false">{{ $t('common.Cancle') }}</Button>
                <Button type="primary" :loading="delLoading" @click="deleteOk">{{ $t('maintenance.Confirmed') }}
                </Button>
            </div>
        </Modal>
        <Modal :mask-closable="false"
            v-model="confirmFaultCodeShowF"
            :title="`${$t('fault.Confirmremind')}`"
        >
            <Row class="enableContent">
                <Col span="24" class="enableContentInner">
                    <img width="95px" src="~images/event/pair.png" alt=""/>
                </Col>
                <Col span="24" class="enableTips">
                    <span>启用后将按计划继续生成任务，是否确定启用？</span>
                </Col>
            </Row>
            <div slot="footer">
                <Button type="default" @click="disabledCancel">{{ $t('common.Cancle') }}</Button>
                <Button type="primary" :loading="disabledLoading" @click="disabledOk">
                    {{ $t('maintenance.Confirmed') }}
                </Button>
            </div>
        </Modal>
        <Modal :mask-closable="false"
            v-model="create"
            :title="`${$t('common.Edit')}`"
        >
            <Form class="formList" :model="formItem" label-position="top" inline>
                <FormItem :label="`${$t('ledger.EquipmentType')}:`" class="item" required>
                    <Select v-model="formItem.classification" filterable clearable
                            :placeholder="`${$t('common.inputInfo')}`">
                        <Option v-for="(item,index) of classification" :value="item.key" :key="index">{{
                                item.name
                            }}
                        </Option>
                    </Select>
                </FormItem>
                <FormItem :label="`${$t('maintenance.MaintenanceItem')}:`" required>
                    <Input type="text" v-model="formItem.materialCode" :placeholder="`${$t('common.inputInfo')}`"
                           class="inputBorder" :maxlength="32"></Input>
                </FormItem>
                <FormItem :label="`${$t('maintenance.Frequency')}:`" class="item" required>
                    <Select v-model="formItem.period" filterable clearable :placeholder="`${$t('common.inputInfo')}`">
                        <Option v-for="(item,index) of period" :value="item.key" :key="index">{{ item.name }}</Option>
                    </Select>
                </FormItem>
                <FormItem :label="`${$t('spareParts.Specification')}:`">
                    <Input type="text" v-model="formItem.materialCode" :placeholder="`${$t('common.inputInfo')}`"
                           class="inputBorder" :maxlength="32"></Input>
                </FormItem>
                <FormItem :label="`${$t('maintenance.Checkmethods')}:`">
                    <Input type="text" v-model="formItem.materialCode" :placeholder="`${$t('common.inputInfo')}`"
                           class="inputBorder" :maxlength="32"></Input>
                </FormItem>
                <FormItem :label="`${$t('maintenance.Checktools')}:`">
                    <Input type="text" v-model="formItem.materialCode" :placeholder="`${$t('common.inputInfo')}`"
                           class="inputBorder" :maxlength="32"></Input>
                </FormItem>
                <FormItem :label="`${$t('maintenance.UpperLimit')}:`">
                    <Input type="text" v-model="formItem.materialCode" :placeholder="`${$t('common.inputInfo')}`"
                           class="inputBorder" :maxlength="32"></Input>
                </FormItem>
                <FormItem :label="`${$t('maintenance.LowerLimit')}:`">
                    <Input type="text" v-model="formItem.materialCode" :placeholder="`${$t('common.inputInfo')}`"
                           class="inputBorder" :maxlength="32"></Input>
                </FormItem>
                <FormItem :label="`${$t('maintenance.Unit')}:`">
                    <Input type="text" v-model="formItem.materialCode" :placeholder="`${$t('common.inputInfo')}`"
                           class="inputBorder" :maxlength="32"></Input>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="default" @click="create = false">{{ $t('common.Cancle') }}</Button>
                <Button type="primary" @click="addOk">{{ $t('maintenance.Confirmed') }}</Button>
            </div>
        </Modal>
        <Modal :mask-closable="false"
            v-model="actualShowF"
            title="禁用记录"
            width="1200"
        >
            <Table :columns="receiveCol" :data="receivedataArr"></Table>
        </Modal>
    </div>
</template>

<script>
import toggleTableOperation from "@/mixins/toggleTableOperation";
import search from "@/components/curd/searchList.vue";

export default {
    name: 'waitConfirmed',
    mixins:[toggleTableOperation],
    components: { search },
    props: ['device', 'invalidPlanList', 'invalidPlanTotal', 'permission', 'planIds'],
    data() {
        return {
          customCacheKey:"planwaitConfirmed",
            text: '',
            planId: '',
            delId: '',
            delIds: this.planIds,
            status: '',
            disabledStatus: '',
            total: this.invalidPlanTotal,
            pageSize: 10,
            pageNum: 1,
            pageSizeOption: [10, 20, 30, 40],
            delLoading: false,
            delFaultCodeShowF: false,//是否显示删除弹窗
            confirmFaultCodeShowF: false,
            disabledLoading: false,
            create: false,
            actualShowF: false,
            searchParams: {},
            formItem: {},
            formInline: {
                disableCycle: '',
                reason: ''
            },
            levelList: [
                {name: "一级保养", key: 1},
                {name: "二级保养", key: 2},
                {name: "三级保养", key: 3},
            ],
            ruleValidate: {
                disableCycle: [
                    {required: true, type: 'number', message: "请输入禁用周期", trigger: "blur"},
                ]
            },
            classification: [
                {name: 'CNC', key: 'CNC'},
                {name: 'PLC', key: 'PLC'},
                {name: 'IPC', key: 'IPC'},
            ],
            receiveCol: [
                {title: '禁用时间', key: 'createTime'},
                {title: '禁用人', key: 'createName'},
                {title: '禁用周期(月)', key: 'disableCycle'},
                {title: '禁用原因', key: 'reason'},
                {title: '启用时间', key: 'enableTime'},
                {title: '启用人', key: 'updateName'}
            ],
            period: [
                {name: '月度', key: 'month'},
                {name: '季度', key: 'quarter'},
                {name: '年度', key: 'year'},
            ],
            category: [
                {label: 'A', value: 'A'},
                {label: 'B', value: 'B'},
                {label: 'C', value: 'C'},
            ],
            cycle: [
                {name: "全部", key: ""},
                {name: "日", key: "1"},
                {name: "周", key: "2"},
                {name: "月", key: "3"},
                {name: "季度", key: "4"},
                {name: "半年度", key: "5"},
                {name: "年度", key: "6"},
                {name: "班次", key: "7"},
                {name: "计时", key: "8"},
            ],
            searchData: [
                // {
                //     title: "安装位置",
                //     key: "installPosition",
                //     type: "cascader",
                //     dicUrl: "/basic/organization/findListByToken?level=0",
                //     params: {
                //         label: "name",
                //         value: "code",
                //         children: "children"
                //     }
                // },
                {
                    title: "计划",
                    key: "planName"
                },
                {
                    title: "设备等级",
                    key: "categoryName",
                    type: "select",
                    dicData: [
                        { label: 'A', value: 'A' },
                        { label: 'B', value: 'B' },
                        { label: 'C', value: 'C' },
                    ]
                },
                {
                    title: "设备类别",
                    key: "deviceType",
                    dicUrl:'/dms/faultCategory/dictList?name=设备类别',
                    type:'select',
                    params:{
                        label:'value',
                        value:'value'
                    }
                },
                {
                    title: "保养级别",
                    key: "itemLevel",
                    type: "select",
                    dicData:[
                        { label: "一级保养", value: 1 },
                        { label: "二级保养", value: 2 },
                        { label: "三级保养", value: 3 },
                    ]
                },
                {
                    title: "保养周期",
                    key: "cycleUnit",
                    type: "select",
                    dicData: [
                        { name: "全部", key: "" },
                        { name: "日", key: "1" },
                        { name: "周", key: "2" },
                        { name: "月", key: "3" },
                        { name: "季度", key: "4" },
                        { name: "半年度", key: "5" },
                        { name: "年度", key: "6" },
                        { name: "班次", key: "7" },
                        { name: "计时", key: "8" },
                    ],
                    params:{
                        label:'name',
                        value:'name'
                    }
                },
                {
                    title: "设备编号",
                    key: "deviceNo",
                },
            ],
            columns: [
                {
                    type: 'selection',
                    align: 'center',
                    width: 60
                },
                {
                    title: `${this.$t('计划')}`,
                    key: 'planName',
                    width: 200,
                    align: "left",
                    tooltip: true,
                    resizable: true,
                },
                {
                    title: `${this.$t('设备等级')}`,
                    key: 'categoryName',
                    minWidth: 160,
                    align: "center",
                    tooltip: true,
                    resizable: true,
                    render: (h, params) => {
                        return h('div', [
                            h('span', {}, params.row.categoryName)
                        ])
                    }
                },
              {
                title: `${this.$t('设备类别')}`,
                key: "deviceType",
                minWidth: 180,
                align: "center",
                tooltip: true,
                resizable: true,
              },
                // {title: '保养位置', key: 'maintainPosition', minWidth: 100,align: "center"},
                {
                    title: `${this.$t('保养级别')}`,
                    key: "itemLevelName",
                    minWidth: 160,
                    align: "center",
                    tooltip: true,
                    resizable: true,
                    render: (h, params) => {
                        return h('div', [
                            h('span', {}, this.levelList.find(val => val.key === params.row.itemLevel).name)
                        ])
                    }
                },
                {
                    title: `${this.$t('保养周期')}`,
                    key: "triggerCycleName",
                    minWidth: 160,
                    align: "center",
                    tooltip: true,
                    resizable: true,
                    render: (h, params) => {
                        return h('div', [
                            h('span', {}, this.cycle.find(val => Number(val.key) === Number(params.row.triggerCycle)).name)
                        ])
                    }
                },
                // {title: '保养方式', key: 'maintainName', minWidth: 100,align: "center", tooltip: true},
                {
                    title: `${this.$t('触发间隔')}`,
                    key: 'triggerCycleText',
                    minWidth: 140,
                    align: "center",
                    tooltip: true,
                  resizable: true,
                },
                {
                    title: `${this.$t('首次生成时间')}`,
                    key: 'firstTime',
                    minWidth: 200,
                    align: "center",
                    tooltip: true,
                  resizable: true,
                },
                {
                    title: `${this.$t('计划截止时间')}`,
                    key: 'planEndTime',
                    minWidth: 200,
                    align: "center",
                    tooltip: true,
                  resizable: true,
                },
                {
                    title: `${this.$t('任务存活时间')}`,
                    key: 'effectiveHourText',
                    minWidth: 200,
                    align: "center",
                    tooltip: true,
                  resizable: true,
                },
                {
                    title: `${this.$t('禁用记录')}`,
                    key: 'disableNum',
                    minWidth: 140,
                    align: "center",
                    tooltip: true,
                    resizable: true,
                    render: (h, params) => {
                        if (params.row.disableNum > 0) {
                            return h('div', [
                                h('a', {
                                    style: {},
                                    on: {
                                        click: () => {
                                            this.getActualNum(params.row)
                                        }
                                    }
                                }, params.row.disableNum)
                            ])
                        } else {
                            return h('div', [
                                h('a', {}, params.row.disableNum)
                            ])
                        }
                    }
                },
                {
                    title: `${this.$t('创建人')}`,
                    key: 'realname',
                    minWidth: 160,
                    align: "center",
                    tooltip: true,
                    resizable: true,
                },
                {
                    title: `${this.$t('创建时间')}`,
                    key: 'createTime',
                    minWidth: 200,
                    align: "center",
                    tooltip: true,
                    resizable: true,
                },
                {
                    title: `${this.$t('common.operation')}`,
                    slot: "action",
                    fixed: 'right',
                    minWidth: this.util.autoWidth(330,370),
                    align: 'center'
                },
            ],
            data: this.invalidPlanList,
            receivedataArr: [],
            deviceNameList: [],
          deviceTypeList: [],
            position: []
        }
    },
    watch: {
        // device(newVal) {
        //   this.category = newVal
        // },
        invalidPlanList(newVal) {
            this.data = newVal
        },
        invalidPlanTotal(newVal) {
            this.total = newVal
        },
        planIds(newVal) {
            this.delIds = newVal
        },
    },
  created() {
    this.getTableColumnsWidth(this.columns)
  },
  mounted() {
    this.getFaultCategory("设备类型")
  },
  methods: {
    deviceNameChange(val) {
      if (val) {
        this.searchParams.deviceType = val
      }
    },
    getSearch(arg){
        this.searchParams=JSON.parse(JSON.stringify(arg[0]))
        const {installPosition}=this.searchParams;
        if (installPosition && installPosition.length > 0) {
            this.searchParams.installPosition=[installPosition.at(-1)]
        }else delete this.searchParams.installPosition;
        this.changeNum()
    },
    //获取故障数据
    getFaultCategory(name) {
      this.axios({
        method: 'get',
        url: '/dms/faultCategory/basicDict',
        params: {name}
      }).then(res => {
        if (res.code === 200) {

          if (name === '故障分类') {
            this.faultCategoryList = res.data.map(item => {
              if (item.value) return item;
            })
          } else if (name === '设备类型') {
            this.deviceTypeList = res.data.map(item => {
              if (item.value) return item;
            })
          }
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}))
        }
      })
    },
        getDeviceNameList(deviceName) {
            if (deviceName) {
                this.axios({
                    method: 'get',
                    url: '/dms/dcmMaintainItem/selectDeviceNames',
                    params: {
                        deviceName
                    }
                }).then(res => {
                    if (res.code == 200) {
                        this.deviceNameList = res.data.map(val => ({
                            label: val,
                            value: val
                        }))
                    }
                })
            }
        },
        onSelectChange(selection) {
            let myArray = [];
            selection.map((item) => {
                myArray.push(item.id);
            });

            this.delIds = myArray;
        },
        deleteOk() {
            this.delLoading = true
            if (this.status == 0) {
                this.axios({
                    method: 'delete',
                    url: '/dms/dcmMaintainPlan/delete',
                    params: {
                        id: this.delId
                    }
                }).then(res => {
                    if (res.code === 200) {
                        this.searchList()
                        this.$Message.success(({content: '删除成功！', duration: 2, closable: true}));
                    } else {
                        this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                    }
                }).finally(() => {
                    this.delLoading = false
                    this.delFaultCodeShowF = false
                })
            } else {
                this.axios({
                    method: 'delete',
                    url: '/dms/dcmMaintainPlan/deleteBatch',
                    params: {
                        ids: this.delIds.toString()
                    }
                }).then(res => {
                    if (res.code === 200) {
                        this.searchList()
                        this.$Message.success(({content: '批量删除成功！', duration: 2, closable: true}));
                    } else {
                        this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                    }
                }).finally(() => {
                    this.delLoading = false
                    this.delFaultCodeShowF = false
                })
            }


        },
        confirm(row) {
            //点击展示提示删除弹窗
            this.confirmFaultCodeShowF = true;
            this.planId = row.id
            this.disabledStatus = 0
        },
        deleteRow(row) {
            //点击展示提示删除弹窗
            this.delFaultCodeShowF = true;
            this.delId = row.id
            this.status = 0
        },
        handleBatchDelete() {
            //点击展示提示删除弹窗
            this.delFaultCodeShowF = true;
            this.status = 1
        },
        handleBatchDisabled() {
            this.disabledStatus = 1
            this.confirmFaultCodeShowF = true
        },
        disabledCancel() {
            this.confirmFaultCodeShowF = false
        },
        disabledOk() {
            this.disabledLoading = true
            if (this.disabledStatus == 0) {
                let data = {
                    planId: this.planId,
                }
                this.axios({
                    method: 'post',
                    url: '/dms/dcmMaintainDisableRecord/enable',
                    data
                }).then(res => {
                    
                    if (res.code === 200) {
                        this.searchList()
                        this.$Message.success(({content: '启用成功！', duration: 2, closable: true}));
                    } else {
                        this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                    }
                }).finally(() => {
                    this.confirmFaultCodeShowF = false
                    this.disabledLoading = false
                })
            } else {
                let data = {
                    planIds: this.delIds.toString(),
                }
                this.axios({
                    method: 'post',
                    url: '/dms/dcmMaintainDisableRecord/batchEnable',
                    data
                }).then(res => {
                    
                    if (res.code === 200) {
                        this.searchList()
                        this.$Message.success(({content: '批量启用成功！', duration: 2, closable: true}));
                    } else {
                        this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                    }
                }).finally(() => {
                    this.confirmFaultCodeShowF = false
                    this.disabledLoading = false
                })
            }

        },
        look(row) {
            this.$emit('changeDetailVisible', true, row.id)
        },
        getActualNum(row) {
            if (this.permission.dcmMaintainDisableRecordList) {
                this.actualShowF = true
                this.getActualDetail(row.id)
                console.log(row, 'row')
            }

        },
        getActualDetail(planId) {
            this.axios({
                method: 'get',
                url: '/dms/dcmMaintainDisableRecord/list',
                params: {
                    planId
                }
            }).then(res => {
                
                if (res.code === 200) {
                    this.receivedataArr = res.data
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            }).finally(() => {
                this.delLoading = false
                this.delFaultCodeShowF = false
            })
        },
        addOk() {
        },
    resetInfo(){
      this.searchParams = {}
      this.$refs.CascaderInfo.value = []
      this.changeNum();
    },
        //分页
        changeNum() {
            this.pageNum = 1;
            this.searchList();
        },
        changePageSize(pageSize) {
            this.pageSize = pageSize;
            this.searchList();
        },
        changePageNum(val) {
            this.pageNum = val;
            this.searchList();
        },
        searchList() {
            let data = {
                status: 1,
                pageNo: this.pageNum,
                pageSize: this.pageSize,
            };
            for (let key in this.searchParams) {
                if (key === 'orgId' && this.searchParams['orgId']) {
                    const arr = this.searchParams[key]
                    const {length, last = length - 1} = arr
                    this.$set(data, key, arr[last])
                } else {
                    if (this.searchParams[key]) {
                        this.$set(data, key, this.searchParams[key])
                    }
                }

            }
            this.axios({
                method: 'post',
                url: '/dms/dcmMaintainPlan/list',
                data
            }).then(res => {
                
                if (res.code === 200) {
                    this.data = res.data.list
                    this.total = res.data.total
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        ok() {
        },
        cancel() {
        },
        edit(row) {
            this.$emit('addMaintain', true, row)
        },
    },
}
</script>

<style scoped lang="scss">
/*.waitConfirmed {*/
/*  height: calc(100% - 100px);*/
/*  overflow: scroll;*/
/*}*/
.addModal {
    .addProject {
        .modalTitle {
            position: relative;

            span {
                font-weight: bold;
                font-size: 20px;
            }

            .label {
                display: flex;
                flex-wrap: wrap;

                .item {
                    display: flex;

                    label {
                        width: 150px;
                        height: 100%;
                        background: #F5F6F7;
                    }

                    & > div {
                        width: 330px;
                    }
                }

                .cycle {
                    display: flex;

                    .ivu-form-item-label {
                        width: 150px;
                        height: 100%;
                        background: #F5F6F7;
                    }

                    .ivu-form-item-content {
                        border: 1px solid #EEEEEE;
                        width: 800px;

                        .ivu-checkbox-wrapper {
                            margin-left: 30px;
                        }
                    }
                }
            }
        }

        .modalTitle::before {
            content: '';
            position: absolute;
            width: 3px;
            height: 20px;
            top: 5px;
            left: -10px;
            background: #187BDB;
        }

        .tab {
            display: flex;
            align-items: center;
            flex-wrap: wrap;

            .icon {
                border: 1px solid #187BDB;
                border-radius: 30px;
                padding: 5px 20px 5px 20px;
                display: flex;
                align-items: center;
                margin-left: 20px;
                color: #187BDB;

                i {
                    font-size: 20px;
                    font-weight: bold;
                }
            }
        }
    }
}

</style>
